import { sendVerificationEmail } from '../../../server/utils/email';
import { generateRandomCode } from '../../../server/utils/crypto';

import { users, verificationCodes } from '../../../server/database/schema';

export default defineEventHandler(async (event) => {
  const body = await readBody(event);
  const { email } = body;

  const db = useDrizzle()

  // 检查邮箱是否已注册
  const existingUser = await db.select().from(users).where(eq(users.email, email));
  if (existingUser.length > 0) {
    throw createError({ statusCode: 400, message: 'Email already registered' });
  }

  // 生成6位验证码 (实际生产环境建议使用更安全的二维码token)
  const code = generateRandomCode(6);
  const expiresAt = new Date(Date.now() + 15 * 60 * 1000); // 15分钟有效期

  // 保存验证码到数据库
  await db.insert(verificationCodes).values({
    email,
    code,
    type: 'register',
    expiresAt
  });

  // 发送验证邮件
  await sendVerificationEmail(email, code);

  return { success: true };
});